package com.ruoyi.business.service.impl;

import com.ruoyi.business.domain.CarPackageAudit;
import com.ruoyi.business.service.ICarPackageAuditService;
import com.ruoyi.business.service.IDoneTaskService;
import com.ruoyi.business.service.IProcessDifinitionService;
import com.ruoyi.common.core.page.PageDomain;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.page.TableSupport;
import com.ruoyi.common.utils.ShiroUtils;
import org.activiti.engine.history.HistoricProcessInstance;
import org.activiti.engine.history.HistoricTaskInstance;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class DoneTaskServiceImpl implements IDoneTaskService {
    @Autowired
    private IProcessDifinitionService processDifinitionService;
    @Autowired
    private ICarPackageAuditService carPackageAuditService;

    @Override
    public TableDataInfo selectDoneList(CarPackageAudit carPackageAudit) {
        //统计已办任务总数
        long total = processDifinitionService.getFinishedTaskCountByInstanceAuditUserId(
                CarPackageAudit.DEFINITION_KEY,
                ShiroUtils.getUserId().toString());
        //封装返回对象TableDataInfo
        TableDataInfo tableDataInfo = new TableDataInfo();
        tableDataInfo.setCode(0);
        tableDataInfo.setTotal(total);
        //如果结果数为0，直接返回结果对象
        if(total == 0) {
            return tableDataInfo;
        }

        //如果数量大于0，构建分页参数

        PageDomain pageDomain = TableSupport.buildPageRequest();
        int startIndex = (pageDomain.getPageNum()-1)*pageDomain.getPageSize();
        List<CarPackageAudit> resultList = new ArrayList<>();

        //查询当前用户的已办任务列表
        List<HistoricTaskInstance> historicTaskList = processDifinitionService.getFinishedTaskListByInstanceAuditUserId(
                CarPackageAudit.DEFINITION_KEY,
                ShiroUtils.getUserId().toString(),
                startIndex,
                pageDomain.getPageSize()
        );
        //6.遍历已办任务列表，基于（历史）实例对象得到业务key
        for (HistoricTaskInstance task : historicTaskList) {
            HistoricProcessInstance instance =  processDifinitionService.getHistoryProcessInstanceByInstanceId(task.getProcessInstanceId());
            long businessKey = Long.parseLong(instance.getBusinessKey());
            //7.根据业务key查询审核记录对象
            CarPackageAudit audit = carPackageAuditService.selectCarPackageAuditById(businessKey);
            //8.将任务信息设置到审核记录对象中（任务id，任务名称，完成时间）
            audit.setTaskId(task.getId());
            audit.setTaskName(task.getName());
            audit.setFinishedTime(task.getEndTime());


            resultList.add(audit);
        }
        //9将列表数据设置到结果对象中TableDataInfo
        tableDataInfo.setRows(resultList);
        return tableDataInfo;
    }
}
